package com.cskaoyan.service;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.KeywordMapper;
import com.cskaoyan.utils.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class KeywordServiceImpl implements KeywordService {
    @Autowired
    KeywordMapper keywordMapper;

    @Override
    public ListData list(Integer page, Integer limit, String sort, String order, String keyword, String url) {
        // page 页码
        // limit 当前页的大小
        PageHelper.startPage(page, limit);
        KeywordExample keywordExample = new KeywordExample();
        keywordExample.setOrderByClause(sort + " " + order);
        KeywordExample.Criteria criteria = keywordExample.createCriteria();

        criteria.andDeletedEqualTo(false);

        // 添加关键词查找的条件
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        // 添加连接查找的条件
        if (!StringUtils.isEmpty(url)) {
            criteria.andUrlLike("%" + url + "%");
        }

        List<Keyword> keywordList = keywordMapper.selectByExample(keywordExample);
        PageInfo<Keyword> keywordPageInfo = new PageInfo<>(keywordList);
        long total = keywordPageInfo.getTotal();
        ListData<Keyword> keywordListData = new ListData<>();
        keywordListData.setItems(keywordList);
        keywordListData.setTotal(total);
        return keywordListData;
    }

    // 添加
    @Override
    public Keyword create(Keyword keyword) {
        keyword.setAddTime(DateUtils.getCurrentTime());
        keyword.setUpdateTime(DateUtils.getCurrentTime());
        keywordMapper.insertSelective(keyword);
        return keyword;
    }

    // 编辑
    @Override
    public void update(Keyword keyword) {
        keywordMapper.updateByPrimaryKeySelective(keyword);
    }

    // 删除
    @Override
    public int delete(Keyword keyword) {
        keyword.setDeleted(true);
        return keywordMapper.updateByPrimaryKeySelective(keyword);
    }

}
